package com.weavernorth.updateKaoQin;

import com.weavernorth.retailExperienceAward.service.OperationCheckImpl;
import com.weavernorth.util.Logger4jUtil;
import cpcns.http.HttpResponse;
import org.apache.log4j.Logger;
import sun.rmi.runtime.Log;
import weaver.conn.RecordSet;
import weaver.interfaces.schedule.BaseCronJob;
import weaver.wechat.util.Utils;

import javax.rmi.CORBA.Util;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import static com.weavernorth.retailExperienceAward.utils.sendDataToSapUtils.getUserid;
import static com.weavernorth.util.MyCommonUtils.getUseridByCode;
import static com.weavernorth.util.dateUtils.*;

/**
 * @Author: bruseewang
 * @Package: com.weavernorth.retailExperienceAward
 * @date: 2020/5/28 10:49
 * @description: 定时任务创建：重新计算请假/外出申请/出差申请人员考勤
 */
public class updateKqTimmer extends BaseCronJob {
    public Logger log = Logger4jUtil.getLoggerByName("/Timmer/updateKqTimmer/");
    private String gh;
    private String begindate;
    private String endate;
    public String getGh() {
        return gh;
    }
    public void setGh(String gh) {
        this.gh = gh;
    }
    public String getBegindate() {
        return begindate;
    }
    public void setBegindate(String begindate) {
        this.begindate = begindate;
    }
    public String getEndate() {
        return endate;
    }
    public void setEndate(String endate) {
        this.endate = endate;
    }
    @Override
    public void execute() {
        log.info("定时任务---开始===>");
        //TODO:销假逻辑
        //SELECT FROMDATEDB begindates,TODATEDB enddates FROM kq_flow_split_leaveback WHERE LEAVEBACKREQUESTID='1646050'--1692861'
        //currentnodetype=3:归档
        String strBegin="";
        String strEnd="";
        String strGh="";
        //获取当前日期
        String nowDate = getYearMonthDay();
        String year=nowDate.split("-")[0];
        String month=nowDate.split("-")[1];
        //获取当前日期天数
        String day= nowDate.split("-")[2];
        if (Integer.parseInt(day)>4){//当前日期在4号之后,取本月
            log.info("当前日期在4号之后时：");
            strBegin=year+"-"+month+"-01";
            log.info("开始日期："+strBegin);
            strEnd=nowDate;
            log.info("结束日期："+strEnd);
        }else{
            strBegin=getPreMonthFirstDate();//获取上个月第一天
            log.info("开始日期："+strBegin);
            strEnd=nowDate;
            log.info("结束日期："+strEnd);
        }
        if(begindate!=null){
            if(isValidDate(begindate,"yyyy-MM-dd")){
                strBegin=begindate;
                log.info("日期参数-开始日期："+strBegin);
            }

        }
        if(endate!=null){
            if(isValidDate(endate,"yyyy-MM-dd")) {
                strEnd = endate;
                log.info("日期参数-结束日期："+strEnd);
            }
        }
        if(gh!=null){
            strGh=gh;
        }
        //请假：workflowid = 2048;
        flushLeave(2048,strGh,strBegin,strEnd);
        //出差：workflowid = 17521;
        flushTravel(17521,strGh,strBegin,strEnd);
        //外出：workflowid = 2521;
        flushGoOut(2521,strGh,strBegin,strEnd);

        log.info("定时任务---结束====>");
    }
    /***
     * 外出申请人员考勤刷新
     * @param flowid
     * @param strGh
     * @param strBegin
     * @param strEnd
     */
    private void flushGoOut(int flowid, String strGh, String strBegin, String strEnd) {
        log.info("外出申请人员考勤开始===>");
        RecordSet rs=new RecordSet();
        String strSql="SELECT  n.detail_resourceid userid,n.detail_fromdate begindate,n.detail_todate endate,m.requestid,b.currentnodetype  " +
                "FROM  FORMTABLE_MAIN_120 m,FORMTABLE_MAIN_120_dt1 n,workflow_requestbase b WHERE " +
                "m.id=n.mainid and m.requestid=b.requestid and b.workflowid = "+flowid+"  AND b.currentnodetype = 3  AND to_date(n.detail_fromdate, 'yyyy-mm-dd') BETWEEN to_date('"+strBegin+"','yyyy-mm-dd')  AND to_date('"+strEnd+"','yyyy-mm-dd')" +
                " AND to_date(n.detail_todate, 'yyyy-mm-dd') BETWEEN to_date('"+strBegin+"','yyyy-mm-dd')  AND to_date('"+strEnd+"','yyyy-mm-dd')";
        if(!"".equals(strGh)){
            String strUserid= getUseridByCode(strGh);
            strSql+=" and n.detail_resourceid="+strUserid;
        }
        log.info("执行外出申请人员考勤刷新的sql:"+strSql);
        rs.executeQuery(strSql);
        List<String> request_list=new ArrayList<String>();
        while (rs.next()){
            String strUserid = Utils.null2String(rs.getString("userid"));
            log.info("人员id:"+strUserid);
            String strRequest= Utils.null2String(rs.getString("requestid"));
            log.info("requestId:"+strRequest);
            String begindate = Utils.null2String(rs.getString("begindate"));
            log.info("开始日期:"+begindate);
            String endate = Utils.null2String(rs.getString("endate"));
            log.info("结束日期:"+endate);
            String strUrl="http://oa.chinaerdos.com/hrm/kq/re_flow_now.jsp?requestid="+strRequest+"&workflowid="+flowid;
            String strResult= sendGet(strUrl,log);
            log.info("外出申请requestId="+strRequest+";的处理结果："+strResult);
//            request_list.add(strRequest);
        }
//        if(request_list.size()>0) {
//            log.info("去重前数据："+request_list.size());
//            List<String> list = request_list.stream().distinct().collect(Collectors.toList());//去重
//            log.info("去重后数据："+list.size());
//            log.info("外出申请流程id去重后的集合："+list.toString());
//            for (String strRequest : list) {
//            String strUrl="http://oa.chinaerdos.com/hrm/kq/re_flow_now.jsp?requestid="+strRequest+"&workflowid="+flowid;
//                String strResult= sendGet(strUrl,log);
//                log.info("外出申请requestId="+strRequest+";的处理结果："+strResult);
//            }
//        }
        log.info("外出申请人员考勤结束===>");
    }

    /***
     * 出差申请人员考勤刷新
     * @param flowid
     * @param strGh
     * @param strBegin
     * @param strEnd
     */
    private void flushTravel(int flowid, String strGh, String strBegin, String strEnd) {
        log.info("出差申请人员考勤刷新开始===>");
        RecordSet rs=new RecordSet();
        String strSql="SELECT  m.resourceid userid,m.fromdate begindate,m.todate endate,m.requestid,b.currentnodetype " +
                "FROM  FORMTABLE_MAIN_340 m,workflow_requestbase b WHERE " +
                " m.requestid=b.requestid and b.workflowid = "+flowid+"  AND b.currentnodetype = 3  AND to_date(m.fromdate, 'yyyy-mm-dd') BETWEEN to_date('"+strBegin+"','yyyy-mm-dd')  AND to_date('"+strEnd+"','yyyy-mm-dd')" +
                " AND to_date(m.todate, 'yyyy-mm-dd') BETWEEN to_date('"+strBegin+"','yyyy-mm-dd')  AND to_date('"+strEnd+"','yyyy-mm-dd')";
        if(!"".equals(strGh)){
            String strUserid= getUseridByCode(strGh);
            strSql+=" and m.resourceid="+strUserid;
        }
        log.info("执行出差申请人员考勤刷新的sql:"+strSql);
        rs.executeQuery(strSql);
        List<String> request_list=new ArrayList<>();
        while (rs.next()){
            String strUserid = Utils.null2String(rs.getString("userid"));
            log.info("人员id:"+strUserid);
            String strRequest= Utils.null2String(rs.getString("requestid"));
            log.info("requestId:"+strRequest);
            String begindate = Utils.null2String(rs.getString("begindate"));
            log.info("开始日期:"+begindate);
            String endate = Utils.null2String(rs.getString("endate"));
            log.info("结束日期:"+endate);
            String strUrl="http://oa.chinaerdos.com/hrm/kq/re_flow_now.jsp?requestid="+strRequest+"&workflowid="+flowid;
            String strResult= sendGet(strUrl,log);
            log.info("出差申请requestId="+strRequest+";的处理结果："+strResult);
//            request_list.add(strRequest);
        }
        log.info("出差申请人员考勤刷新结束===>");
    }

    /***
     * 请假申请人员考勤刷新
     * @param flowid
     * @param strGh
     * @param strBegin
     * @param strEnd
     */
    private void flushLeave(int flowid, String strGh, String strBegin, String strEnd) {
        log.info("请假申请人员考勤刷新开始===>");
        RecordSet rs=new RecordSet();
        String strSql="SELECT  n.detail_resourceid userid,n.detail_fromdate begindate,n.detail_todate endate,m.requestid,b.currentnodetype  " +
                "FROM  FORMTABLE_MAIN_110 m,FORMTABLE_MAIN_110_dt1 n,workflow_requestbase b WHERE " +
                "m.id=n.mainid and m.requestid=b.requestid and b.workflowid = "+flowid+"  AND b.currentnodetype = 3  AND to_date(n.detail_fromdate, 'yyyy-mm-dd') BETWEEN to_date('"+strBegin+"','yyyy-mm-dd')  AND to_date('"+strEnd+"','yyyy-mm-dd')" +
                " AND to_date(n.detail_todate, 'yyyy-mm-dd') BETWEEN to_date('"+strBegin+"','yyyy-mm-dd')  AND to_date('"+strEnd+"','yyyy-mm-dd')";
        if(!"".equals(strGh)){
            String strUserid= getUseridByCode(strGh);
            strSql+=" and n.detail_resourceid="+strUserid;
        }
        log.info("执行请假申请人员考勤刷新的sql:"+strSql);
        rs.executeQuery(strSql);
        List<String> request_list=new ArrayList<>();
        while (rs.next()){
            String strUserid = Utils.null2String(rs.getString("userid"));
            log.info("人员id:"+strUserid);
            String strRequest= Utils.null2String(rs.getString("requestid"));
            log.info("requestId:"+strRequest);
            String begindate = Utils.null2String(rs.getString("begindate"));
            log.info("开始日期:"+begindate);
            String endate = Utils.null2String(rs.getString("endate"));
            log.info("结束日期:"+endate);
            String strUrl="http://oa.chinaerdos.com/hrm/kq/re_flow_now.jsp?requestid="+strRequest+"&workflowid="+flowid;
            String strResult= sendGet(strUrl,log);
            log.info("请假申请requestId="+strRequest+";的处理结果："+strResult);
//            request_list.add(strRequest);

        }
        log.info("请假申请人员考勤刷新结束===>");
    }



    //发送GET请求
    public static String sendGet(String url, Logger log) {
        String result = "";
        BufferedReader in = null;
        try {
            String urlName = url;
            URL realUrl = new URL(urlName);
            URLConnection conn = realUrl.openConnection();// 打开和URL之间的连接
            conn.setRequestProperty("accept", "*/*");// 设置通用的请求属性
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
            conn.setConnectTimeout(4000);
            conn.connect();// 建立实际的连接
            in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));// 定义BufferedReader输入流来读取URL的响应
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            log.info("发送GET请求出现异常！" + e);
        } finally {// 使用finally块来关闭输入流
            try {
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                log.info("关闭流异常");
            }
        }
        return result;
    }
}
